/*
 * Copyright (c) 2012, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.bmi.gwt.ws.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.bmi.gwt.ws.server.serialization.ServerPayloadSerializer;

import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.server.rpc.SerializationPolicyProvider;

/**
 * An inbound object designed to receive object of a provided type from a client
 * web socket.
 * 
 * @author Marco Tamburelli
 * 
 * @param <T>
 */
public abstract class ObjectInbound<T extends IsSerializable> extends MessageInbound
{
	private ServerPayloadSerializer<T> serializer;

	/**
	 * Wraps a {@link WsOutbound} object, providing method to send back a
	 * provided object.
	 */
	public class WsOutboundWrapper
	{
		private WsOutbound elem;

		private WsOutboundWrapper(WsOutbound elem)
		{
			this.elem = elem;
		}

		public void close(int status, ByteBuffer data) throws IOException
		{
			this.elem.close(status, data);
		}

		public void flush() throws IOException
		{
			this.elem.flush();
		}

		/**
		 * Serializes and add the serialized payload to the buffer for textual
		 * data.
		 * 
		 * @param object
		 * @throws IOException
		 */
		public void writeObjectMessage(T object) throws IOException
		{
			try
			{
				this.elem.writeTextMessage(CharBuffer.wrap(ObjectInbound.this.serializer.serialize(object)));
			}
			catch (SerializationException e)
			{
				throw new IOException("Problem while serializing object: ", e);
			}
		}
	}

	/**
	 * Constructor
	 * 
	 * @param currentServlet The caller servlet {@link AbstractWebSocketServer}
	 *        is required.
	 */
	public ObjectInbound(final AbstractWebSocketServer currentServlet)
	{
		super();

		this.serializer = new ServerPayloadSerializer<T>()
		{
			@Override
			protected SerializationPolicyProvider getSerializationPolicy()
			{
				return currentServlet;
			}
		};
	}

	@Override
	protected final void onTextMessage(CharBuffer message) throws IOException
	{
		try
		{
			onObjectMessage(this.serializer.deserialize(message.toString()));
		}
		catch (SerializationException e)
		{
			throw new IOException("Problem while deserializeing payload: ", e);
		}
	}

	@Override
	protected final void onBinaryMessage(ByteBuffer message) throws IOException
	{
		throw new UnsupportedOperationException("Binary message not supported.");
	}

	/**
	 * It's invoked when an object received from the client was successfully
	 * deserialized.
	 * 
	 * @param object
	 */
	protected abstract void onObjectMessage(T object);

	/**
	 * Returns an object wrapping the expected {@link WsOutbound}.
	 * 
	 * @return
	 */
	public WsOutboundWrapper getWsOutboundWrapper()
	{
		return new WsOutboundWrapper(getWsOutbound());
	}
}
